﻿using SuperX.Common.Abstract;
using SuperX.DataService;
using SuperX.DataService.Abstract;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;

namespace SuperX.DataService.Helper
{
    public class TagMetaHelper
    {
        public static void SetValue<T>(T Targetobj, IEnumerable<IIOTag> tags, List<FileData> fileDatas)
        {
            Type t = Targetobj.GetType();//获得该类的Type

            //再用Type.GetProperties获得PropertyInfo[],然后就可以用foreach 遍历了
            foreach (PropertyInfo pi in t.GetProperties())
            {
                var value = Targetobj.GetType().GetProperty(pi.Name).GetValue(Targetobj, null);
                string name = pi.Name;//获得属性的名字,后面就可以根据名字判断来进行些自己想要的操作
                                      //获得属性的类型,进行判断然后进行以后的操作,例如判断获得的属性是整数
                var tag = tags.Where(a => a.Name == name).FirstOrDefault();
                FileData fileData = new FileData() { ID = tag.Identity };
                switch (Type.GetTypeCode(pi.PropertyType))
                {
                    case TypeCode.String:
                        fileData.Text = value == null ? string.Empty : value.ToString();
                        break;

                    case TypeCode.Boolean:
                        fileData.Value.Boolean = Convert.ToBoolean(value);
                        break;

                    case TypeCode.Single:
                    case TypeCode.Decimal:
                    case TypeCode.Double:
                        fileData.Value.Single = Convert.ToSingle(value);
                        break;

                    case TypeCode.Int16:
                        fileData.Value.Int16 = Convert.ToInt16(value);
                        break;

                    case TypeCode.Int32:
                        fileData.Value.Int32 = Convert.ToInt32(value);
                        break;

                    case TypeCode.Int64:

                        break;

                    case TypeCode.Byte:
                        fileData.Value.Byte = Convert.ToByte(value);
                        break;

                    case TypeCode.DateTime:
                        fileData.Text = value == null ? string.Empty : value.ToString();
                        break;

                    default:
                        fileData.Text = value == null ? string.Empty : value.ToString();
                        break;
                }
                fileDatas.Add(fileData);
            }
        }
    }
}